import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface FinanceRecord {
  id: string
  type: '收入' | '支出'
  category: string
  subcategory: string
  amount: number
  description: string
  date: string
  paymentMethod: '现金' | '银行卡' | '微信' | '支付宝' | '医保' | '转账'
  relatedId?: string // 关联的患者、药品、设备等ID
  relatedType?: '患者' | '药品' | '设备' | '供应商' | '员工'
  relatedName?: string
  departmentId?: string
  departmentName?: string
  operator: string
  operatorId: string
  status: '待审核' | '已审核' | '已拒绝' | '已入账'
  approver?: string
  approvedAt?: string
  invoiceNumber?: string
  taxAmount?: number
  createdAt: string
  updatedAt: string
}

export interface Budget {
  id: string
  year: number
  quarter?: number
  month?: number
  type: '年度预算' | '季度预算' | '月度预算'
  departmentId?: string
  departmentName?: string
  category: string
  allocated: number
  used: number
  remaining: number
  items: Array<{
    name: string
    allocated: number
    used: number
    description: string
  }>
  status: '草稿' | '已提交' | '已审批' | '执行中' | '已完成'
  createdBy: string
  approvedBy?: string
  createdAt: string
  updatedAt: string
}

export interface Invoice {
  id: string
  number: string
  type: '收入发票' | '支出发票'
  amount: number
  taxRate: number
  taxAmount: number
  totalAmount: number
  issueDate: string
  dueDate: string
  clientId: string
  clientName: string
  clientTaxNumber?: string
  items: Array<{
    name: string
    quantity: number
    unitPrice: number
    amount: number
    taxRate: number
  }>
  status: '草稿' | '已开具' | '已发送' | '已付款' | '已作废'
  notes: string
  createdBy: string
  createdAt: string
  updatedAt: string
}

export const useFinanceStore = defineStore('finance', () => {
  const financeRecords = ref<FinanceRecord[]>([
    {
      id: 'FR001',
      type: '收入',
      category: '门诊收入',
      subcategory: '挂号费',
      amount: 50,
      description: '内分泌科门诊挂号费',
      date: '2024-01-20',
      paymentMethod: '微信',
      relatedId: 'P001',
      relatedType: '患者',
      relatedName: '张三',
      departmentId: 'DEPT001',
      departmentName: '内分泌科',
      operator: '收费员',
      operatorId: 'U001',
      status: '已入账',
      invoiceNumber: 'INV20240120001',
      createdAt: '2024-01-20T09:30:00',
      updatedAt: '2024-01-20T09:30:00'
    },
    {
      id: 'FR002',
      type: '支出',
      category: '药品采购',
      subcategory: '处方药',
      amount: 1500,
      description: '阿司匹林肠溶片采购',
      date: '2024-01-18',
      paymentMethod: '转账',
      relatedId: 'M001',
      relatedType: '药品',
      relatedName: '阿司匹林肠溶片',
      operator: '采购员',
      operatorId: 'U002',
      status: '已审核',
      invoiceNumber: 'PUR20240118001',
      createdAt: '2024-01-18T14:20:00',
      updatedAt: '2024-01-18T16:30:00'
    }
  ])

  const budgets = ref<Budget[]>([
    {
      id: 'BG001',
      year: 2024,
      month: 1,
      type: '月度预算',
      departmentId: 'DEPT001',
      departmentName: '内分泌科',
      category: '运营支出',
      allocated: 200000,
      used: 120000,
      remaining: 80000,
      items: [
        { name: '人员工资', allocated: 100000, used: 60000, description: '医护人员工资' },
        { name: '药品采购', allocated: 50000, used: 30000, description: '常用药品采购' },
        { name: '设备维护', allocated: 30000, used: 20000, description: '医疗设备维护' },
        { name: '其他支出', allocated: 20000, used: 10000, description: '办公用品等' }
      ],
      status: '执行中',
      createdBy: '财务主管',
      approvedBy: '院长',
      createdAt: '2024-01-01T10:00:00',
      updatedAt: '2024-01-20T15:30:00'
    }
  ])

  const invoices = ref<Invoice[]>([
    {
      id: 'INV001',
      number: 'INV20240120001',
      type: '收入发票',
      amount: 500,
      taxRate: 0.06,
      taxAmount: 30,
      totalAmount: 530,
      issueDate: '2024-01-20',
      dueDate: '2024-02-20',
      clientId: 'P001',
      clientName: '张三',
      items: [
        { name: '门诊挂号费', quantity: 1, unitPrice: 50, amount: 50, taxRate: 0.06 },
        { name: '检查费', quantity: 1, unitPrice: 200, amount: 200, taxRate: 0.06 },
        { name: '药费', quantity: 1, unitPrice: 250, amount: 250, taxRate: 0.06 }
      ],
      status: '已开具',
      notes: '',
      createdBy: '收费员',
      createdAt: '2024-01-20T09:30:00',
      updatedAt: '2024-01-20T09:30:00'
    }
  ])

  const currentRecord = ref<FinanceRecord | null>(null)
  const searchQuery = ref('')
  const filterType = ref('')
  const filterCategory = ref('')
  const filterStatus = ref('')
  const filterDateRange = ref<[string, string] | null>(null)
  const loading = ref(false)

  // 获取财务记录
  const getFinanceRecords = async (params?: any) => {
    loading.value = true
    try {
      await new Promise(resolve => setTimeout(resolve, 500))
      return financeRecords.value
    } finally {
      loading.value = false
    }
  }

  // 根据ID获取财务记录
  const getFinanceRecordById = (id: string) => {
    return financeRecords.value.find(r => r.id === id)
  }

  // 添加财务记录
  const addFinanceRecord = async (record: Omit<FinanceRecord, 'id' | 'createdAt' | 'updatedAt'>) => {
    loading.value = true
    try {
      const newRecord: FinanceRecord = {
        ...record,
        id: `FR${Date.now()}`,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
      financeRecords.value.unshift(newRecord)
      
      // 更新相关预算
      if (record.departmentId && record.type === '支出') {
        await updateBudgetUsage(record.departmentId, record.category, record.amount)
      }
      
      return newRecord
    } finally {
      loading.value = false
    }
  }

  // 更新财务记录
  const updateFinanceRecord = async (id: string, updates: Partial<FinanceRecord>) => {
    loading.value = true
    try {
      const index = financeRecords.value.findIndex(r => r.id === id)
      if (index > -1) {
        financeRecords.value[index] = {
          ...financeRecords.value[index],
          ...updates,
          updatedAt: new Date().toISOString()
        }
        return financeRecords.value[index]
      }
      throw new Error('财务记录不存在')
    } finally {
      loading.value = false
    }
  }

  // 审核财务记录
  const approveFinanceRecord = async (id: string, approver: string) => {
    return updateFinanceRecord(id, {
      status: '已审核',
      approver,
      approvedAt: new Date().toISOString()
    })
  }

  // 拒绝财务记录
  const rejectFinanceRecord = async (id: string, approver: string) => {
    return updateFinanceRecord(id, {
      status: '已拒绝',
      approver,
      approvedAt: new Date().toISOString()
    })
  }

  // 搜索财务记录
  const searchFinanceRecords = (query: string) => {
    searchQuery.value = query
    if (!query) return financeRecords.value
    
    return financeRecords.value.filter(record => 
      record.description.includes(query) ||
      record.relatedName?.includes(query) ||
      record.departmentName?.includes(query) ||
      record.operator.includes(query)
    )
  }

  // 按类型筛选
  const filterRecordsByType = (type: string) => {
    filterType.value = type
    if (!type) return financeRecords.value
    
    return financeRecords.value.filter(record => record.type === type)
  }

  // 按分类筛选
  const filterRecordsByCategory = (category: string) => {
    filterCategory.value = category
    if (!category) return financeRecords.value
    
    return financeRecords.value.filter(record => record.category === category)
  }

  // 按状态筛选
  const filterRecordsByStatus = (status: string) => {
    filterStatus.value = status
    if (!status) return financeRecords.value
    
    return financeRecords.value.filter(record => record.status === status)
  }

  // 按日期范围筛选
  const filterRecordsByDateRange = (dateRange: [string, string] | null) => {
    filterDateRange.value = dateRange
    if (!dateRange) return financeRecords.value
    
    const [startDate, endDate] = dateRange
    return financeRecords.value.filter(record => 
      record.date >= startDate && record.date <= endDate
    )
  }

  // 预算管理
  const getBudgets = () => {
    return budgets.value
  }

  const addBudget = async (budget: Omit<Budget, 'id' | 'used' | 'remaining' | 'createdAt' | 'updatedAt'>) => {
    loading.value = true
    try {
      const newBudget: Budget = {
        ...budget,
        id: `BG${Date.now()}`,
        used: 0,
        remaining: budget.allocated,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
      budgets.value.unshift(newBudget)
      return newBudget
    } finally {
      loading.value = false
    }
  }

  const updateBudget = async (id: string, updates: Partial<Budget>) => {
    loading.value = true
    try {
      const index = budgets.value.findIndex(b => b.id === id)
      if (index > -1) {
        const budget = budgets.value[index]
        budgets.value[index] = {
          ...budget,
          ...updates,
          remaining: (updates.allocated || budget.allocated) - (updates.used || budget.used),
          updatedAt: new Date().toISOString()
        }
        return budgets.value[index]
      }
      throw new Error('预算不存在')
    } finally {
      loading.value = false
    }
  }

  const updateBudgetUsage = async (departmentId: string, category: string, amount: number) => {
    const budget = budgets.value.find(b => 
      b.departmentId === departmentId && 
      b.category === category && 
      b.status === '执行中'
    )
    
    if (budget) {
      budget.used += amount
      budget.remaining = budget.allocated - budget.used
      budget.updatedAt = new Date().toISOString()
      
      // 更新预算项目
      const item = budget.items.find(i => i.name === category)
      if (item) {
        item.used += amount
      }
    }
  }

  // 发票管理
  const getInvoices = () => {
    return invoices.value
  }

  const addInvoice = async (invoice: Omit<Invoice, 'id' | 'createdAt' | 'updatedAt'>) => {
    loading.value = true
    try {
      const newInvoice: Invoice = {
        ...invoice,
        id: `INV${Date.now()}`,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
      invoices.value.unshift(newInvoice)
      return newInvoice
    } finally {
      loading.value = false
    }
  }

  const updateInvoice = async (id: string, updates: Partial<Invoice>) => {
    loading.value = true
    try {
      const index = invoices.value.findIndex(i => i.id === id)
      if (index > -1) {
        invoices.value[index] = {
          ...invoices.value[index],
          ...updates,
          updatedAt: new Date().toISOString()
        }
        return invoices.value[index]
      }
      throw new Error('发票不存在')
    } finally {
      loading.value = false
    }
  }

  // 统计分析
  const getFinancialSummary = (startDate?: string, endDate?: string) => {
    let records = financeRecords.value
    
    if (startDate && endDate) {
      records = records.filter(r => r.date >= startDate && r.date <= endDate)
    }
    
    const totalIncome = records
      .filter(r => r.type === '收入' && r.status === '已入账')
      .reduce((sum, r) => sum + r.amount, 0)
    
    const totalExpense = records
      .filter(r => r.type === '支出' && r.status === '已入账')
      .reduce((sum, r) => sum + r.amount, 0)
    
    const profit = totalIncome - totalExpense
    
    const incomeByCategory = records
      .filter(r => r.type === '收入' && r.status === '已入账')
      .reduce((acc, r) => {
        acc[r.category] = (acc[r.category] || 0) + r.amount
        return acc
      }, {} as Record<string, number>)
    
    const expenseByCategory = records
      .filter(r => r.type === '支出' && r.status === '已入账')
      .reduce((acc, r) => {
        acc[r.category] = (acc[r.category] || 0) + r.amount
        return acc
      }, {} as Record<string, number>)
    
    const byPaymentMethod = records
      .filter(r => r.status === '已入账')
      .reduce((acc, r) => {
        acc[r.paymentMethod] = (acc[r.paymentMethod] || 0) + r.amount
        return acc
      }, {} as Record<string, number>)
    
    return {
      totalIncome,
      totalExpense,
      profit,
      profitMargin: totalIncome > 0 ? (profit / totalIncome * 100).toFixed(2) : '0',
      incomeByCategory,
      expenseByCategory,
      byPaymentMethod,
      recordCount: records.length
    }
  }

  const getDepartmentFinancials = (departmentId: string, startDate?: string, endDate?: string) => {
    let records = financeRecords.value.filter(r => r.departmentId === departmentId)
    
    if (startDate && endDate) {
      records = records.filter(r => r.date >= startDate && r.date <= endDate)
    }
    
    const income = records
      .filter(r => r.type === '收入' && r.status === '已入账')
      .reduce((sum, r) => sum + r.amount, 0)
    
    const expense = records
      .filter(r => r.type === '支出' && r.status === '已入账')
      .reduce((sum, r) => sum + r.amount, 0)
    
    return {
      income,
      expense,
      profit: income - expense,
      recordCount: records.length
    }
  }

  const getMonthlyTrend = (months: number = 12) => {
    const endDate = new Date()
    const startDate = new Date()
    startDate.setMonth(endDate.getMonth() - months)
    
    const monthlyData = []
    
    for (let i = months - 1; i >= 0; i--) {
      const date = new Date()
      date.setMonth(endDate.getMonth() - i)
      const monthKey = date.toISOString().substring(0, 7) // YYYY-MM
      
      const monthRecords = financeRecords.value.filter(r => 
        r.date.startsWith(monthKey) && r.status === '已入账'
      )
      
      const income = monthRecords
        .filter(r => r.type === '收入')
        .reduce((sum, r) => sum + r.amount, 0)
      
      const expense = monthRecords
        .filter(r => r.type === '支出')
        .reduce((sum, r) => sum + r.amount, 0)
      
      monthlyData.push({
        month: monthKey,
        income,
        expense,
        profit: income - expense
      })
    }
    
    return monthlyData
  }

  const getBudgetUtilization = () => {
    return budgets.value.map(budget => {
      const utilizationRate = budget.allocated > 0 ? (budget.used / budget.allocated * 100).toFixed(1) : '0'
      return {
        ...budget,
        utilizationRate: parseFloat(utilizationRate)
      }
    })
  }

  // 获取统计数据
  const getFinanceStats = () => {
    const summary = getFinancialSummary()
    const pendingApproval = financeRecords.value.filter(r => r.status === '待审核').length
    const overBudgetDepartments = budgets.value.filter(b => b.used > b.allocated).length
    
    return {
      ...summary,
      pendingApproval,
      overBudgetDepartments,
      totalBudgets: budgets.value.length,
      totalInvoices: invoices.value.length
    }
  }

  return {
    financeRecords,
    budgets,
    invoices,
    currentRecord,
    searchQuery,
    filterType,
    filterCategory,
    filterStatus,
    filterDateRange,
    loading,
    getFinanceRecords,
    getFinanceRecordById,
    addFinanceRecord,
    updateFinanceRecord,
    approveFinanceRecord,
    rejectFinanceRecord,
    searchFinanceRecords,
    filterRecordsByType,
    filterRecordsByCategory,
    filterRecordsByStatus,
    filterRecordsByDateRange,
    getBudgets,
    addBudget,
    updateBudget,
    updateBudgetUsage,
    getInvoices,
    addInvoice,
    updateInvoice,
    getFinancialSummary,
    getDepartmentFinancials,
    getMonthlyTrend,
    getBudgetUtilization,
    getFinanceStats
  }
}, {
  persist: {
    key: 'finance-store',
    storage: localStorage,
    paths: ['financeRecords', 'budgets', 'invoices']
  }
})